import 'package:flutter/foundation.dart';
import '../models/product.dart';

class CartProvider with ChangeNotifier {
  // 购物车商品及数量
  final Map<Product, int> _items = {};
  
  // 获取购物车商品
  Map<Product, int> get items => {..._items};
  
  // 获取商品总数
  int get itemCount => _items.values.fold(0, (sum, quantity) => sum + quantity);
  
  // 获取总价
  double get totalAmount {
    return _items.entries.fold(
      0,
      (sum, item) => sum + (item.key.price * item.value),
    );
  }

  // 添加商品到购物车
  void addItem(Product product) {
    if (_items.containsKey(product)) {
      _items[product] = _items[product]! + 1;
    } else {
      _items[product] = 1;
    }
    notifyListeners();
  }

  // 从购物车移除商品
  void removeItem(Product product) {
    if (_items.containsKey(product)) {
      if (_items[product]! > 1) {
        _items[product] = _items[product]! - 1;
      } else {
        _items.remove(product);
      }
      notifyListeners();
    }
  }

  // 清空购物车
  void clear() {
    _items.clear();
    notifyListeners();
  }
} 